from fastapi import APIRouter, Depends
from sqlalchemy.orm import joinedload

from apps.models import SysRole
from apps.system import cruds, schemas
from apps.system.params.role import RoleParams
from core.auth import Auth, FullAdminAuth
from core.dependencies import IdList
from core.response import SuccessResponse, ErrorResponse

router = APIRouter(prefix="/role")


@router.get("/list", summary="获取角色列表")
async def list_roles(
        params: RoleParams = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["system.role.list"]))
):
    datas, count = await cruds.RoleDal(auth.db).get_datas(**params.dict(), v_return_count=True)
    return SuccessResponse(datas, count=count)


@router.get("/options", summary="获取所有角色")
async def list_roll_options(
        auth: Auth = Depends(FullAdminAuth())
):
    return SuccessResponse(await cruds.RoleDal(auth.db).get_select_datas())


@router.post("/create", summary="创建角色")
async def create_role(
        data: schemas.RoleIn,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.role.create"]))
):
    return SuccessResponse(
        await cruds.RoleDal(auth.db).create_data(data=data),
        msg="创建成功"
    )


@router.put("/update/{data_id}", summary="更新角色")
async def update_role(
        data_id: int,
        data: schemas.RoleIn,
        auth: Auth = Depends(FullAdminAuth(permissions=["system.role.update"]))
):
    if 1 == data_id:
        return ErrorResponse("不能修改管理员角色")
    return SuccessResponse(
        await cruds.RoleDal(auth.db).put_data(data_id, data),
        msg="修改成功"
    )


@router.delete("/delete", summary="删除角色")
async def delete_role(
        ids: IdList = Depends(),
        auth: Auth = Depends(FullAdminAuth(permissions=["system.role.delete"]))
):
    if 1 in ids.ids:
        return ErrorResponse("不能删除管理员角色")
    await cruds.RoleDal(auth.db).delete_datas(ids.ids, v_soft=False)
    return SuccessResponse(msg="删除成功")


@router.get("/{data_id}", summary="获取角色信息")
async def get_role(
        data_id: int,
        auth: Auth = Depends(FullAdminAuth())
):
    model = SysRole
    options = [joinedload(model.menus), joinedload(model.depts)]
    schema = schemas.RoleOut
    return SuccessResponse(await cruds.RoleDal(auth.db).get_data(data_id, v_options=options, v_schema=schema))
